package com.chixing.ih.module.system.controller;

import com.chixing.ih.json.ReData;
import com.chixing.ih.json.ReJson;
import com.chixing.ih.json.StateValue;
import com.chixing.ih.module.system.pojo.Admin;
import com.chixing.ih.module.system.pojo.User;
import com.chixing.ih.module.system.pojo.dto.UserDTO;
import com.chixing.ih.module.system.pojo.dto.UserRegisterDTO;
import com.chixing.ih.module.system.service.IAdminService;
import com.chixing.ih.module.system.service.ISystemService;
import com.chixing.ih.module.system.service.IUserService;
import com.chixing.ih.util.*;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;

import static com.chixing.ih.module.system.service.Impl.SystemServiceImpl.REGISTER_TEMPLATE;

/**
 * @author 刘岩
 * @version 1.0
 * @Desc Practice makes perfect
 * @date 2020/9/21 21:36
 */
@Api(tags = "系统登陆注册相关Api")
@RestController
@RequestMapping("/sys")
public class SystemController {


    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private SendNoteUtil sendNoteUtil;


    @Autowired
    private ISystemService systemService;

    @Autowired
    private IUserService userService;

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    IAdminService adminService;

    @Autowired
    HttpUtil httpUtil;

    @Autowired
    RedisUtil redisUtil;


    /**
     * 用户通过手机注册发送手机验证码
     *
     * @param phone
     * @param response
     * @return
     */
    @ApiOperation(value = "发送验证码接口", notes = "普通用户通过手机注冊发送手机验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "用户手机注册手机号", required = true, dataType = "String")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "验证码发送成功"),
            @ApiResponse(code = 408, message = "验证码发送失败，账号已存在")
    })
    @GetMapping(value = "/note/{phone}")
    public HashMap<String, Object> sendNote(@PathVariable("phone") String phone, HttpServletResponse response) {
        //验证手机号是否已经注册
        boolean accountExisted = userService.isAccountExisted(phone);
        if (accountExisted) {
            System.out.println("验证码已经发送");
            sendNoteUtil.sendNoteMessgae(phone, REGISTER_TEMPLATE);
            return ReJson.returnJson(ReData.SUCCESS.code, ReData.SUCCESS.msg);
        }
        System.out.println("账号已存在");
        return ReJson.returnJson(ReData.FAIL_NORMAL1.code, ReData.FAIL_NORMAL1.msg);

//            同一个签名，对同一个手机号的发送频率
//            1分钟内短信发送条数不超过：
//            1
//            1小时内短信发送条数不超过：
//            5
//            1个自然日内短信发送条数不超过：
//            10
    }

    /**
     * 用户邮箱注册刷新图片验证码
     *
     * @param response
     * @return
     */
    @ApiOperation(value = "图片验证码接口", notes = "普通用户通过邮箱注册刷新图片验证码")
    @GetMapping(value = "/kaptcha")
    public String getKaptcha(HttpServletResponse response) {
        // 生成验证码
        String AuthCode = kaptchaProducer.createText();
        redisUtil.set("AuthCode", AuthCode);
        BufferedImage image = kaptchaProducer.createImage(AuthCode);
        String base64_png = null;
        try {
            base64_png = Base64Util.getBase64_png(image);
        } catch (IOException e) {
            System.out.println("生成图片验证码异常");
        }
        return base64_png;

    }

    /**
     * 普通用户手机注册
     *
     * @param userRegisterDTO
     * @return
     */
    @ApiOperation(value = "手机号注册接口", notes = "普通用户通过手机号注册账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userAccount", value = "注册账号", required = true, dataType = "string"),
            @ApiImplicitParam(name = "authCode", value = "注册手机验证码", required = true, dataType = "string"),
            @ApiImplicitParam(name = "nickName", value = "注册昵称", required = true, dataType = "string"),
            @ApiImplicitParam(name = "userPassword", value = "注册密码", required = true, dataType = "string")

    })
    @ApiResponses({
            @ApiResponse(code = 408, message = "验证码过期"),
            @ApiResponse(code = 408, message = "验证码错误"),
            @ApiResponse(code = 408, message = "昵称已存在"),
            @ApiResponse(code = 200, message = "注册成功")
    })
    @PostMapping(value = "/phone_register")
    public HashMap<String, Object> phoneRegister(@RequestBody UserRegisterDTO userRegisterDTO) {
        int AuthValue = systemService.verifyAuthCode(userRegisterDTO.getAuthCode(), userRegisterDTO.getUserAccount());
        if (AuthValue == StateValue.STATE_VALUE_THREE) {
            boolean nickNameExisted = userService.isNickNameExisted(userRegisterDTO.getNickName());
            if (nickNameExisted) {
                userRegisterDTO.setPhone(userRegisterDTO.getUserAccount());
                userService.saveUser(userRegisterDTO);
                return ReJson.returnJson(ReData.SUCCESS.code, ReData.SUCCESS.msg);
            } else {
                return ReJson.returnJson(ReData.FAIL_NORMAL3.code, ReData.FAIL_NORMAL3.msg);
            }
        }
        if (AuthValue == StateValue.STATE_VALUE_ONE) {
            return ReJson.returnJson(ReData.FAIL_NORMAL4.code, ReData.FAIL_NORMAL4.msg);
        }
        return ReJson.returnJson(ReData.FAIL_NORMAL6.code, ReData.FAIL_NORMAL6.msg);

    }

    /**
     * 普通用户通过邮箱注册
     *
     * @param userRegisterDTO
     * @return
     */
    @ApiOperation(value = "邮箱注册接口", notes = "普通用户通过邮箱注册账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userAccount", value = "注册账号", required = true, dataType = "string"),
            @ApiImplicitParam(name = "authCode", value = "注册邮箱验证码", required = true, dataType = "string"),
            @ApiImplicitParam(name = "nickName", value = "注册昵称", required = true, dataType = "string"),
            @ApiImplicitParam(name = "userPassword", value = "注册密码", required = true, dataType = "string")

    })
    @ApiResponses({
            @ApiResponse(code = 408, message = "账号已存在"),
            @ApiResponse(code = 408, message = "验证码错误"),
            @ApiResponse(code = 408, message = "昵称已存在"),
            @ApiResponse(code = 200, message = "注册成功")

    })
    @PostMapping(value = "/email_register")
    public HashMap<String, Object> emailRegister(@RequestBody UserRegisterDTO userRegisterDTO) {
        if (userService.isAccountExisted(userRegisterDTO.getUserAccount())) {
            if (userRegisterDTO.getAuthCode().toUpperCase().equals(redisUtil.get("AuthCode"))) {
                if (userService.isNickNameExisted(userRegisterDTO.getNickName())) {
                    userRegisterDTO.setUserEmail(userRegisterDTO.getUserAccount());
                    userService.saveUser(userRegisterDTO);
                    return ReJson.returnJson(ReData.SUCCESS.code, ReData.SUCCESS.msg);
                }
                return ReJson.returnJson(ReData.FAIL_NORMAL3.code, ReData.FAIL_NORMAL3.msg);
            }
            return ReJson.returnJson(ReData.FAIL_NORMAL6.code, ReData.FAIL_NORMAL6.msg);


        }
        return ReJson.returnJson(ReData.FAIL_NORMAL1.code, ReData.FAIL_NORMAL1.msg);


    }

    /**
     * 普通用户登陆
     *
     * @param user
     * @param response
     * @return
     */
    @ApiOperation(value = "普通用户登陆接口", notes = "普通用户登陆账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userAccount", value = "登陆账号", required = true, dataType = "string"),
            @ApiImplicitParam(name = "userPassword", value = "登陆密码", required = true, dataType = "string"),

    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "登陆成功"),
            @ApiResponse(code = 408, message = "账号或密码错误")

    })

    @PostMapping(value = "/userLogin")
    public HashMap<String, Object> userLogin(@RequestBody User user, HttpServletResponse response) {
        UserDTO loginSuccess = userService.isLoginSuccess(user);
        if (loginSuccess != null) {
            httpUtil.setToken(response, jwtUtil.createJWT(String.valueOf(loginSuccess.getUser().getUserId())));
            return ReJson.returnJson(ReData.SUCCESS.code, ReData.SUCCESS.msg, loginSuccess);
        }
        return ReJson.returnJson(ReData.FAIL_NORMAL2.code, ReData.FAIL_NORMAL2.msg);
    }

    /**
     * 管理员登陆
     *
     * @param admin
     * @param response
     * @return
     */
    @ApiOperation(value = "管理员登陆接口", notes = "管理员登陆账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adminAccount", value = "登陆账号", required = true, dataType = "string"),
            @ApiImplicitParam(name = "adminPassword", value = "登陆密码", required = true, dataType = "string"),

    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "登陆成功"),
            @ApiResponse(code = 408, message = "账号或密码错误")

    })
    @PostMapping(value = "/adminLogin")
    public HashMap<String, Object> adminLogin(@RequestBody Admin admin, HttpServletResponse response) {
        Admin loginSuccess = adminService.isLoginSuccess(admin);
        if (loginSuccess != null) {
            httpUtil.setToken(response, jwtUtil.createJWT(String.valueOf(loginSuccess.getAdminId())));
            return ReJson.returnJson(ReData.SUCCESS.code, ReData.SUCCESS.msg, loginSuccess);
        }
        return ReJson.returnJson(ReData.FAIL_NORMAL2.code, ReData.FAIL_NORMAL2.msg);
    }

}
